class Movie < ActiveRecord::Base
  validates_presence_of :title
  validates_presence_of :description
  validates_inclusion_of :rating, :in => %w( G PG PG-13 R NC-17 )
  validates_length_of :description, :minimum => 10
  validates_uniqueness_of :title

  @@today = nil

  def pretendTodayIs(today)
    @@today = Date.parse(today.to_s)
  end
  def Movie.pretendTodayIs(today)
    @@today = Date.parse(today.to_s)
  end

  def appropriate_for_birthdate?(birthdate)
    # convert rating to the minimum age
    minAge = case self.rating
      when "PG-13" then 13
      when "R" then 17
      when "NC-17" then 17
      else 0 # G and PG
    end
    return Movie.rating_appropriate_for_birthdate?(minAge, birthdate)
  end
  
  def Movie.find_all_appropriate_for_birthdate(birthdate)
    allowedRatings = ["G", "PG"]
    allowedRatings += ["PG-13"] if rating_appropriate_for_birthdate?(13, birthdate)
    allowedRatings += ["R", "NC-17"] if rating_appropriate_for_birthdate?(17, birthdate)
    return self.find(:all, :conditions => {:rating => allowedRatings})
  end

  private

  def Movie.rating_appropriate_for_birthdate?(minAge, birthdate)
    # pretend today is @@today for debugging purpose
    today = @@today ? @@today : Date.today
    # compare dates (conversion to Date class is neededd because we shouldn't be
    # comapring hour/minute/second of birthdate to current time)
    return today.years_ago(minAge) >= Date.parse(birthdate.to_s)
  end

end
